package com.lagou.rpcdemo.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author srh
 * @date 2020/10/18
 **/
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;
    private CustomSerializer serializer;


    public RpcDecoder(Class<?> clazz, CustomSerializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int readLength = byteBuf.readableBytes();
        byte[] buffer = new byte[readLength];
        byteBuf.readBytes(buffer);

        String jsonString = new String(buffer);
        String newJsonString = jsonString.substring(getOffset(jsonString));

        Object deserialize = serializer.deserialize(clazz, newJsonString.getBytes(StandardCharsets.UTF_8));
        list.add(deserialize);
    }

    private int getOffset(String jsonString) {
        return jsonString.indexOf("{");
    }
}
